// 权限配置中心模板配置文件
const db = uniCloud.database()

// 表格列配置
const tableColumns = {
	permission: [
		{ key: 'permission_id', label: '权限标识', width: 150, align: 'center' },
		{ key: 'permission_name', label: '权限名称', align: 'center' },
		{ key: 'comment', label: '备注', align: 'center', formatter: (val) => val || '-' },
		{ key: 'create_date', label: '创建时间', width: 180, align: 'center', type: 'date' }
	],
	role: [
		{ key: 'role_id', label: '角色ID', width: 150, align: 'center' },
		{ key: 'role_name', label: '角色名称', align: 'center' },
		{ key: 'permission_list', label: '权限', align: 'center', type: 'tags', tagType: 'primary' },
		{ key: 'comment', label: '备注', align: 'center', formatter: (val) => val || '-' },
		{ key: 'create_date', label: '创建时间', width: 180, align: 'center', type: 'date' }
	],
	user: [
		{ key: 'username', label: '用户名', width: 120, align: 'center' },
		{ key: 'nickname', label: '昵称', width: 120, align: 'center', formatter: (val) => val || '-' },
		{ key: 'mobile', label: '手机号', width: 120, align: 'center', formatter: (val) => val || '-' },
		{ key: 'role_list', label: '角色', align: 'center', type: 'tags', tagType: 'success' },
		{ key: 'status', label: '状态', width: 100, align: 'center', type: 'status', statusMap: { 0: '正常', 1: '禁用' } },
		{ key: 'last_login_date', label: '最后登录', width: 180, align: 'center', type: 'date' }
	],
	menu: [
		{ key: 'sort', label: '排序', width: 80, align: 'center' },
		{ key: 'name', label: '名称', width: 200 },
		{ key: 'menu_id', label: '标识', align: 'center' },
		{ key: 'url', label: 'URL', align: 'center', formatter: (val) => val || '-' },
		{ key: 'enable', label: '启用', width: 100, align: 'center', type: 'switch' }
	]
}

// 表单字段配置
const formFields = {
	permission: [
		{ key: 'permission_id', label: '权限ID', type: 'input', required: true, placeholder: '唯一标识，不可重复', disabled: (formData) => !!formData._id },
		{ key: 'permission_name', label: '权限名称', type: 'input', required: true, placeholder: '权限显示名称' },
		{ key: 'comment', label: '备注', type: 'textarea', placeholder: '权限说明' }
	],
	role: [
		{ key: 'role_id', label: '角色ID', type: 'input', required: true, placeholder: '唯一标识，不可重复', disabled: (formData) => !!formData._id },
		{ key: 'role_name', label: '角色名称', type: 'input', required: true, placeholder: '角色显示名称' },
		{ key: 'permission', label: '分配权限', type: 'checkbox', collection: 'uni-id-permissions', field: 'permission_name as text, permission_id as value', multiple: true },
		{ key: 'menu', label: '分配菜单', type: 'checkbox', collection: 'opendb-admin-menus', field: 'name as text, menu_id as value', multiple: true },
		{ key: 'comment', label: '备注', type: 'textarea', placeholder: '角色说明' }
	],
	user: [
		{ key: 'username', label: '用户名', type: 'input', required: true, placeholder: '请输入用户名', disabled: (formData) => !!formData._id },
		{ key: 'nickname', label: '昵称', type: 'input', required: true, placeholder: '请输入昵称' },
		{ key: 'password', label: '初始密码', type: 'input', required: true, placeholder: '请输入初始密码', show: (formData) => !formData._id },
		{ key: 'role', label: '分配角色', type: 'checkbox', collection: 'uni-id-roles', field: 'role_name as text, role_id as value', multiple: true },
		{ key: 'mobile', label: '手机号', type: 'input', placeholder: '请输入手机号' },
		{ key: 'email', label: '邮箱', type: 'input', placeholder: '请输入邮箱' },
		{ key: 'status', label: '是否启用', type: 'switch', valueMap: { true: 0, false: 1 } }
	],
	menu: [
		{ key: 'name', label: '菜单名称', type: 'input', required: true, placeholder: '菜单显示名称' },
		{ key: 'menu_id', label: '菜单标识', type: 'input', required: true, placeholder: '唯一标识，不可重复', disabled: (formData) => !!formData._id },
		{ key: 'url', label: 'URL', type: 'input', placeholder: '菜单链接地址' },
		{ key: 'parent_id', label: '父菜单', type: 'select', collection: 'opendb-admin-menus', field: 'name as text, menu_id as value', clearable: true },
		{ key: 'sort', label: '排序', type: 'number', placeholder: '数字越小越靠前' },
		{ key: 'enable', label: '是否启用', type: 'switch' }
	]
}

// 模块配置
export const moduleConfig = {
	permission: {
		name: '权限管理',
		collection: 'uni-id-permissions',
		field: 'permission_id,permission_name,comment,create_date',
		orderby: 'create_date desc',
		pageSize: 20,
		supportBatchDelete: true,
		tableColumns: tableColumns.permission,
		formFields: formFields.permission,
		searchFields: ['permission_id', 'permission_name'],
		defaultFormData: {},
		beforeSave: null,
		afterLoad: null
	},
	role: {
		name: '角色管理',
		collection: [
			db.collection('uni-id-roles').field('role_id,role_name,permission,comment,create_date').getTemp(),
			db.collection('uni-id-permissions').field('permission_id,permission_name').getTemp()
		],
		orderby: 'create_date desc',
		pageSize: 20,
		supportBatchDelete: true,
		tableColumns: tableColumns.role,
		formFields: formFields.role,
		searchFields: ['role_id', 'role_name'],
		defaultFormData: { permission: [], menu: [] },
		beforeSave: null,
		afterLoad: (data) => {
			// 处理权限列表显示
			for (let i = 0; i < data.length; i++) {
				const item = data[i]
				if (Array.isArray(item.permission)) {
					item.permission_list = item.permission.map(p => p.permission_name || p)
				} else {
					item.permission_list = []
				}
			}
			return data
		},
		formDataTransform: {
			// 编辑时转换数据
			edit: (item) => ({
				...item,
				permission: item.permission ? item.permission.map(p => p.permission_id || p) : [],
				menu: item.menu ? (Array.isArray(item.menu) ? item.menu : [item.menu]) : []
			})
		}
	},
	user: {
		name: '用户管理',
		collection: [
			// 联表查询时，field 方法只能使用字符串形式，明确排除 password 字段
			db.collection('uni-id-users').field('username,nickname,mobile,role,status,last_login_date').getTemp(),
			db.collection('uni-id-roles').field('role_id,role_name').getTemp()
		],
		orderby: 'last_login_date desc',
		pageSize: 20,
		supportBatchDelete: true,
		tableColumns: tableColumns.user,
		formFields: formFields.user,
		searchFields: ['username', 'nickname', 'mobile'],
		defaultFormData: { role: [], status: 0 },
		beforeSave: async (data, isEdit) => {
			// 用户保存前处理
			if (isEdit) {
				delete data.password
				return { data, useUniId: false }
			} else {
				if (!data.password) {
					throw new Error('请输入初始密码')
				}
				return { data, useUniId: true }
			}
		},
		afterLoad: (data) => {
			// 处理角色列表显示，并删除敏感字段
			for (let i = 0; i < data.length; i++) {
				const item = data[i]
				// 删除敏感字段，避免权限校验错误
				// uni-id-users 集合的受保护字段：password, token, dcloud_appid, wx_unionid, wx_openid 等
				const sensitiveFields = ['password', 'token', 'dcloud_appid', 'wx_unionid', 'wx_openid', 'qq_openid', 'ali_openid', 'baidu_openid', 'toutiao_openid']
				sensitiveFields.forEach(field => {
					if (item[field] !== undefined) {
						delete item[field]
					}
				})
				if (Array.isArray(item.role)) {
					item.role_list = item.role.map(r => r.role_name || r)
				} else {
					item.role_list = []
				}
			}
			return data
		},
		formDataTransform: {
			edit: (item) => ({
				...item,
				role: item.role ? item.role.map(r => r.role_id || r) : [],
				status: item.status || 0
			})
		}
	},
	menu: {
		name: '菜单管理',
		collection: 'opendb-admin-menus',
		orderby: 'create_date asc',
		pageSize: 20000,
		supportBatchDelete: false,
		tableColumns: tableColumns.menu,
		formFields: formFields.menu,
		searchFields: ['name', 'menu_id', 'url'],
		defaultFormData: { enable: true, sort: 0 },
		beforeSave: null,
		afterLoad: (data) => {
			// 处理菜单层级显示
			const getDepth = (menus, id, depth = 0) => {
				const menu = menus.find(m => m.menu_id === id)
				if (menu && menu.parent_id) {
					return 1 + getDepth(menus, menu.parent_id, depth)
				}
				return depth
			}
			// 保存原始名称，用于显示层级
			for (let i = 0; i < data.length; i++) {
				const item = data[i]
				if (!item._originalName) {
					item._originalName = item.name
				}
				const depth = getDepth(data, item.menu_id)
				item.name = '　'.repeat(depth) + (depth > 0 ? '|-' : '') + item._originalName
			}
			return data
		},
		beforeDelete: async (id) => {
			// 删除前检查
			const menu = await db.collection('opendb-admin-menus').doc(id).get()
			if (menu.data) {
				const childMenus = await db.collection('opendb-admin-menus')
					.where({ parent_id: menu.data.menu_id })
					.get()
				if (childMenus.data.length > 0) {
					throw new Error('该菜单下有子菜单，无法删除')
				}
				if (menu.data.menu_id === 'system_menu' || menu.data.menu_id === 'system_management') {
					throw new Error('不能删除系统内置菜单')
				}
			}
		}
	}
}

// 获取所有标签页配置，按指定顺序：用户、角色、菜单、权限
const tabOrder = ['user', 'role', 'menu', 'permission']
export const tabs = tabOrder.map(key => ({
	key,
	name: moduleConfig[key] ? moduleConfig[key].name : key
}))

